package com.mg.yygh.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import com.mg.yygh.enums.PaymentTypeEnum;
import com.mg.yygh.enums.RefundStatusEnum;
import com.mg.yygh.model.order.OrderInfo;
import com.mg.yygh.model.order.PaymentInfo;
import com.mg.yygh.model.order.RefundInfo;
import com.mg.yygh.order.service.OrderService;
import com.mg.yygh.order.service.PaymentService;
import com.mg.yygh.order.service.RefundInfoService;
import com.mg.yygh.order.service.WeixinService;
import com.mg.yygh.order.utils.ConstantPropertiesUtils;
import com.mg.yygh.order.utils.HttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author M_Dragon
 * @date 2022/9/30/030 16:54
 */
@Service
public class WeixinServiceImpl implements WeixinService {

    @Autowired
    private OrderService orderService;
    @Autowired
    private PaymentService paymentService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RefundInfoService refundInfoService;


    // 生成支付二维码
    @Override
    public Map<String, Object> createNative(Long orderId) {
       try {
           // 从redis获取获取数据
           Map payMap = (Map) redisTemplate.opsForValue().get(orderId.toString());
           if(null != payMap) return payMap;
           // 1.查询订单信息
           OrderInfo orderInfo = orderService.getById(orderId);
           // 2.向支付表添加信息
           paymentService.savePaymentInfo(orderInfo, PaymentTypeEnum.WEIXIN.getStatus());
           // 3.设置参数，调用微信二维码生成接口
           // 把参数转换成xml格式，使用商户key进行加密
           Map paramMap = new HashMap<>();
           paramMap.put("appid", ConstantPropertiesUtils.APPID);
           paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);
           paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
           String body = orderInfo.getReserveDate() + "就诊"+ orderInfo.getDepname();
           paramMap.put("body", body);
           paramMap.put("out_trade_no", orderInfo.getOutTradeNo());
           //paramMap.put("total_fee", order.getAmount().multiply(new BigDecimal("100")).longValue()+"");
           paramMap.put("total_fee", "1");
           paramMap.put("spbill_create_ip", ConstantPropertiesUtils.PRESENTIP);
           paramMap.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify");
           paramMap.put("trade_type", "NATIVE");
           // 4.调用微信生成二维码接口，httpClient调用
           HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
           httpClient.setXmlParam(WXPayUtil.generateSignedXml(paramMap,ConstantPropertiesUtils.PARTNERKEY));
           httpClient.setHttps(true);
           httpClient.post();
           // 5.返回相关数据
           String xml = httpClient.getContent();
           Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
           // 6.封装返回结果集
           Map map = new HashMap<>();
           map.put("orderId", orderId);
           map.put("totalFee", orderInfo.getAmount());
           map.put("resultCode", resultMap.get("result_code"));
           map.put("codeUrl", resultMap.get("code_url")); // 二维码地址
           if(null != resultMap.get("result_code")) {
               //微信支付二维码2小时过期，可采取2小时未支付取消订单
               redisTemplate.opsForValue().set(orderId.toString(), map, 120, TimeUnit.MINUTES);
           }
           return map;
        } catch (Exception e) {
            e.printStackTrace();
           return null;
        }
    }

    // 调用微信接口实现支付状态查询
    @Override
    public Map<String, String> queryPayStatus(Long orderId) {
        try {
            // 1.获取订单信息
            OrderInfo orderInfo = orderService.getById(orderId);
            // 2.封装提交请求参数
            Map paramMap = new HashMap<>();
            paramMap.put("appid", ConstantPropertiesUtils.APPID);
            paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);
            paramMap.put("out_trade_no", orderInfo.getOutTradeNo());
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
            // 3.设置请求内容
            HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            httpClient.setXmlParam(WXPayUtil.generateSignedXml(paramMap,ConstantPropertiesUtils.PARTNERKEY));
            httpClient.setHttps(true);
            httpClient.post();
            // 4.返还结果集
            String xml = httpClient.getContent();
            Map resultMap = WXPayUtil.xmlToMap(xml);
            return resultMap;
        }catch (Exception e){
            return null;
        }
    }

    // 微信退款
    @Override
    public Boolean refund(Long orderId) {
        try {
            // 获取预退款订单的支付记录
            PaymentInfo paymentInfo = paymentService.getPaymentInfo(orderId, PaymentTypeEnum.WEIXIN.getStatus());
            // 添加退款记录
            RefundInfo refundInfo = refundInfoService.saveRefundInfo(paymentInfo);
            // 判断该订单是否已经退款
            if(refundInfo.getRefundStatus().intValue() == RefundStatusEnum.REFUND.getStatus().intValue()){
                // 已经退款
                return true;
            }
            // 封装请求上传参数
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("appid",ConstantPropertiesUtils.APPID);       //公众账号ID
            paramMap.put("mch_id",ConstantPropertiesUtils.PARTNER);   //商户编号
            paramMap.put("nonce_str",WXPayUtil.generateNonceStr());
            paramMap.put("transaction_id",paymentInfo.getTradeNo()); //微信订单号
            paramMap.put("out_trade_no",paymentInfo.getOutTradeNo()); //商户订单编号
            paramMap.put("out_refund_no","tk"+paymentInfo.getOutTradeNo()); //商户退款单号
//       paramMap.put("total_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
//       paramMap.put("refund_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
            paramMap.put("total_fee","1");
            paramMap.put("refund_fee","1");
            String paramXml = WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY);
            // 设置调用接口内容
            HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/secapi/pay/refund");
            httpClient.setHttps(true);
            httpClient.setXmlParam(paramXml);
            // 设置证书信息
            httpClient.setCert(true);
            httpClient.setCertPassword(ConstantPropertiesUtils.PARTNER);
            httpClient.post();
            // 接受返回结果集
            String resultXml = httpClient.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(resultXml);
            if(null != resultMap && WXPayConstants.SUCCESS.equalsIgnoreCase(resultMap.get("result_code"))){
                refundInfo.setCallbackTime(new Date());
                refundInfo.setTradeNo(resultMap.get("refund_id"));
                refundInfo.setRefundStatus(RefundStatusEnum.REFUND.getStatus());
                refundInfo.setCallbackContent(JSONObject.toJSONString(resultMap));
                refundInfoService.updateById(refundInfo);
                return true;
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
